package com.offcn.oauth.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin() // 使用架构提供的登录界面
                .loginPage("/oauth/login") // 自定义登录界面
                .and()
                .authorizeRequests()
                .antMatchers("/userOauth/login").permitAll() // 放行
                .anyRequest()
                .authenticated() // 所有的请求都需要认证
                .and()
                .csrf().disable(); // 关闭跨域攻击，实现跨域
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers(
                "/css/**",
                "/data/**",
                "/fonts/**",
                "/img/**",
                "/js/**",
                "/plugins/**",
                "/oauth/login"
        );
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

//    @Bean
//    @Override
//    public UserDetailsService userDetailsServiceBean() throws Exception {
//        return myUserDetailsService();
//    }
//
    private UserDetailsService myUserDetailsService(){
        UserDetails admin = User.withUsername("admin")
                .password(passwordEncoder().encode("123456"))
                .authorities("ADMIN", "USER").build();
        UserDetails xiaobai = User.withUsername("xiaobai")
                .password(passwordEncoder().encode("123456"))
                .authorities("USER").build();
        UserDetails xiaohei = User.withUsername("xiaohei")
                .password(passwordEncoder().encode("123456"))
                .authorities("ADMIN", "USER").build();
        return new InMemoryUserDetailsManager(admin,xiaobai,xiaohei);
    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}
